//
//  PaperReportViewController.swift
//  Exam-iOS
//
//  Created by lishengfeng on 2018/3/14.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import UIKit
import Then
import SnapKit
import RxCocoa
import RxSwift
import RxDataSources



let PaperReportCompleteNotification = "PaperReportCompleteNotification"

class PaperReportViewController: ViewController, LeftBarButtonItemable {
    
    var collectionView: UICollectionView!
    var errorAnalysisBtn: UIButton!
    var allAnalysisBtn: UIButton!
    
    ///重考
    var reExamHandle: VoidBlock?
    
    var vm: PaperReportViewModel!
    var datasource: RxCollectionViewSectionedReloadDataSource<PaperReportSection>!
    
    init(_ paper: PaperModel) {
        self.vm = PaperReportViewModel.init(paper)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        bindUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setPopRecognizerEnable(false)
    }
    
    private func initUI() {
        title = "答题报告"
        
        ///设置返回按钮
        setLeftItem { [weak self] in
            //返回上上层页面
            if let controllers = self?.navigationController?.viewControllers {
                if controllers.count >= 3 {
                    let vc = controllers[controllers.count - 3]
                    self?.navigationController?.popToViewController(vc, animated: true)
                }
            }
            else {
                self?.navigationController?.popViewController(animated: true)
            }
        }
        
        _ = UIBarButtonItem.init().then { (item) in
            item.title = "重考"
            item.tintColor = UIColor.white
            navigationItem.rightBarButtonItem = item
            
            item.rx.tap.bind { [weak self] in
                guard let strongSelf = self else { return }
                lsf_alert("确认重新考试？", viewController: strongSelf, cancelTitle: "取消", destructiveTitle: "重考", handle: { [weak self] (title) in
                    if title == "重考" {
                        //重考
                        self?.reExamHandle?()
                    }
                })
            }.disposed(by: disposeBag)
        }
      
        let flowLayout = LSFEqualCellSpaceFlowLayout.init().then { (layout) in
            layout.alignType = .left
            layout.minimumLineSpacing = 20
            layout.cellSpacing = 20
            layout.itemSize = CGSize.init(width: 30, height: 30)
            layout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: 20, right: 15)
            layout.footerReferenceSize = CGSize.init(width: k_screen_width, height: 11)
        }
        
        collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: flowLayout).then({ (cv) in
            cv.backgroundColor = UIColor.white
            cv.register(PaperReportCell.classForCoder(), forCellWithReuseIdentifier: "PaperReportCell")
            cv.register(PaperReportHeaderView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "PaperReportHeaderView")
            cv.register(PaperReportScoreView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "PaperReportScoreView")
            cv.register(PaperReportFooterView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "PaperReportFooterView")
            
            view.addSubview(cv)
            cv.snp.makeConstraints({ (maker) in
                maker.top.leading.trailing.equalToSuperview()
            })
            
            cv.rx.setDelegate(self).disposed(by: disposeBag)
        })
        
        let bottomView = UIView().then({ (view) in
            view.backgroundColor = UIColor.white
            
            self.view.addSubview(view)
            view.snp.makeConstraints({ (maker) in
                maker.leading.trailing.equalToSuperview()
                maker.top.equalTo(collectionView.snp.bottom)
                maker.height.equalTo(56)
                maker.bottom.equalToSuperview().offset(0 - safeAreaInsets().bottom)
            })
        })
        
        errorAnalysisBtn = UIButton.init(type: .custom).then({ (btn) in
            btn.setTitle("错题解析", for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            btn.setTitleColor(Config.default.themeColor, for: .normal)
            btn.layer.borderColor = Config.default.themeColor.cgColor
            btn.layer.borderWidth = 1.0
            btn.layer.cornerRadius = 18
            btn.clipsToBounds = true
            
            bottomView.addSubview(btn)
            btn.snp.makeConstraints({ (maker) in
                maker.size.equalTo(CGSize.init(width: 136, height: 36))
                maker.centerY.equalToSuperview()
                maker.centerX.equalToSuperview().offset(-79)
            })
        })
        
        allAnalysisBtn = UIButton.init(type: .custom).then({ (btn) in
            btn.setTitle("全部解析", for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            btn.setTitleColor(Config.default.themeColor, for: .normal)
            btn.layer.borderColor = Config.default.themeColor.cgColor
            btn.layer.borderWidth = 1.0
            btn.layer.cornerRadius = 18
            btn.clipsToBounds = true
            
            bottomView.addSubview(btn)
            btn.snp.makeConstraints({ (maker) in
                maker.size.equalTo(CGSize.init(width: 136, height: 36))
                maker.centerY.equalToSuperview()
                maker.centerX.equalToSuperview().offset(79)
            })
        })
    }
    
    private func bindUI() {
        
        // 错题解析
        errorAnalysisBtn.rx.tap.bind {[weak self] in
            if let paper = self?.vm.paper.paperForErrorAnalysis() {
                let title = self?.vm.paper.title
                guard let paperId = self?.vm.paper.paperId else { return }
                let paperVC = PaperViewController.init(paperId, paper: paper, status: .analysis, title: title)
                self?.navigationController?.pushViewController(paperVC, animated: true)
            }
            }.disposed(by: disposeBag)
        
        // 全部解析
        allAnalysisBtn.rx.tap.bind {[weak self] in
            if let paper = self?.vm.paper.paperForAllAnalysis() {
                let title = self?.vm.paper.title
                guard let paperId = self?.vm.paper.paperId else { return }
                let paperVC = PaperViewController.init(paperId, paper: paper, status: PaperStatus.analysis, title: title)
                self?.navigationController?.pushViewController(paperVC, animated: true)
            }
            }.disposed(by: disposeBag)
        
        
        
        
        // Cell
        datasource = RxCollectionViewSectionedReloadDataSource.init(configureCell: { (ds, cv, ip, item) -> UICollectionViewCell in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "PaperReportCell", for: ip) as! PaperReportCell
            cell.set(item.index, result: item.userAnswerResult)
            return cell
        }, configureSupplementaryView: { [weak self] (ds, cv, kind, ip) -> UICollectionReusableView in
            
            if kind == UICollectionElementKindSectionHeader {
                var headerView: PaperReportHeaderView!
                if ip.section == 0 {
                    let view = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "PaperReportScoreView", for: ip) as! PaperReportScoreView
                    view.set(single: self?.vm.paper.singleChoiceScore,
                             multi: self?.vm.paper.multiChoiceScore,
                             trueOfFalse: self?.vm.paper.trueOrFalseScore,
                             shortAnswer: self?.vm.paper.shortAnswerScore,
                             analysis: self?.vm.paper.analysisQuestScore,
                             officialDoc: self?.vm.paper.officialDocScore,
                             calcQuest: self?.vm.paper.calcQuestScore,
                             total: self?.vm.paper.totalScore,
                             time: self?.vm.paper.timeInterval,
                             hasSelfScore: self?.vm.hasSelfeScore)
                    view.selfReportHandle = { [weak self] in
                        self?.selfReport()
                    }
                    headerView = view
                }
                else {
                    
                    headerView = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "PaperReportHeaderView", for: ip) as! PaperReportHeaderView
                }
                if let sections = self?.vm.vmDatas.value {
                    if sections.count > ip.section {
                        let section = sections[ip.section]
                        headerView.set(section.header)
                    }
                }
                return headerView
            }
            else {
                let view = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "PaperReportFooterView", for: ip) as! PaperReportFooterView

                return view
            }
        })
        
        ///自评分完成通知消息
        _ = NotificationCenter.default.rx.notification(Notification.Name(PaperReportCompleteNotification)).takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (notification) in
            self?.selfReportHandle()
        })
        
        vm.vmDatas.asObservable().bind(to: collectionView.rx.items(dataSource: datasource)).disposed(by: disposeBag)
        vm.transform()
    }
    
    ///点击自评分
    func selfReport() {
        let paper = self.vm.paper.paperForSelfReport()
        
        if paper.paperItems?.count == 0 {
            lsf_alert("没有可评分的主观题")
            return
        }
        
        let title = self.vm.paper.title
        guard let paperId = self.vm.paper.paperId else { return }
        let paperVC = PaperViewController.init(paperId, paper: paper, status: PaperStatus.selfReported, title: title)
        self.navigationController?.pushViewController(paperVC, animated: true)
    }
    
    func selfReportHandle() {
        vm.hasSelfeScore = true
        vm.paper.calculateSelfReportScore()
        collectionView.reloadData()
    }
}
extension PaperReportViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        var height:CGFloat = 39
        if section == 0 {
            height = 157
        }
        
        return CGSize.init(width: k_screen_width, height: height)
    }
}
